package red.lixiang.controller;

import red.lixiang.dao.MemberDAO;
import red.lixiang.model.Address;
import red.lixiang.model.BaseInfo;
import red.lixiang.model.Member;
import red.lixiang.model.WeChatInfo;
import red.lixiang.service.MemberService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import static red.lixiang.base.APPCONST.BACK_URL;
import static red.lixiang.base.APPCONST.MEMBER_INFO;
import static red.lixiang.base.APPCONST.WECHAT_INFO;

@Controller
public class MemberController  {

    private   final Logger logger = Logger.getLogger(MemberController.class.getName());

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private MemberService memberService;


    @RequestMapping("/member/memberaddress/{id}")
    public String showAddress(Model model, @PathVariable Integer id){
        logger.info("come in showAddress");
        BaseInfo baseInfo = memberService.getMemberAddress(id);
        List<Address> addressList = (List<Address>)baseInfo.getObject();
        model.addAttribute("address",addressList);
        model.addAttribute("memberid",id);
        return "memberaddress";
    }

    @RequestMapping("/member/showaddaddress/{id}")
    public String showAddAddress(Model model, @PathVariable Integer id){
        logger.info("come in showAddAddress");
        model.addAttribute("memberid",id);
        return "add-address";
    }

    @GetMapping("/member/getDefaultAddress/{id}")
    @ResponseBody
    public String getDefaultAddress(@PathVariable Integer id){ //memberId
        logger.info("come in getDefaultAddress");
        BaseInfo baseInfo = memberService.getDefaultAddress(id);
        return JSON.toJSONString(baseInfo);
    }

    @GetMapping("/member/deleteAddress/{id}")
    @ResponseBody
    public String deleteAddress(@PathVariable Integer id){ // addressId
        logger.info("come in deleteAddress");
        BaseInfo baseInfo = memberService.deleteAddress(id);
        return JSON.toJSONString(baseInfo);
    }

    @PostMapping("/member/updateAddress")
    @ResponseBody
    public String updateAddress(Address address){ // addressId
        logger.info("come in updateAddress");
        BaseInfo baseInfo = memberService.updateAddress(address);
        return JSON.toJSONString(baseInfo);
    }

    @RequestMapping("/member/addaddress")
    public String addAddress(HttpServletRequest request, HttpServletResponse response, Model model, Address address) {
        logger.info("come in addAddress");
        memberService.addNewAddress(address);
        System.out.println(address.getMobilePhone());
        BaseInfo baseInfo = memberService.getMemberAddress(address.getMemberId());
        List<Address> addressList = (List<Address>) baseInfo.getObject();
        model.addAttribute("address", addressList);
        model.addAttribute("memberid",address.getMemberId());
        return "memberaddress";
    }

    @GetMapping("/member/showMemberPage")
    public String showMemberPage(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        logger.info("come in member");
        Map<String , Object > map = new HashMap<>();
        //先查看session里面有没有对应的用户信息
        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);
        if(weChatInfo==null){
            //如果微信用户信息用空，则先放callbackUrl ,然后调用微信接口进行登录
            request.getSession().setAttribute(BACK_URL,request.getRequestURI());
            response.sendRedirect("/wx/getAccessCode");
            return null;
        }else {
            //如果有对应的微信用户信息，则看对应数据库中有没有会员数据
            //如果有会员数据，则直接取出，如果没有的话，则需要手机号和验证码来进行绑定
            BaseInfo baseInfo = memberService.getMemberByWxOpenId(weChatInfo.getOpenid());
            Member member = (Member) baseInfo.getObject();
            if(member==null || member.getMemberMobile().startsWith("9") ){
                //如果会员信息为空，跳转到会员登录界面
                request.getSession().setAttribute(BACK_URL,request.getRequestURI());
                response.sendRedirect("/account/showLogin?type=1");
                return null;
            }else{
                //如果有会员信息，则将会员相关信息存放于session中
                request.getSession().setAttribute(MEMBER_INFO,baseInfo.getObject());
                map.put("memberInfo",baseInfo.getObject());

            }
            model.addAllAttributes(map);
        }

        return "member";
    }

    @GetMapping("/member/getAllMember")
    @ResponseBody
    public String getAllMember(){
        logger.info("come in getAllMember");
        List<Member> memberList = memberDAO.getAllMember();
        HashMap<String ,List> map = new HashMap<>();
        map.put("data",memberList);
        return JSON.toJSONString(map);
    }

    @GetMapping("/member/getMember/{word}")
    @ResponseBody
    public String getMemberByCardOrMobile(@PathVariable String word){
        logger.info("come in getMemberByCardOrMobile");
        BaseInfo baseInfo = memberService.getMemberByCardOrMobile(word);
        return JSON.toJSONString(baseInfo);
    }

    @GetMapping("/member/recharge")
    @ResponseBody
    public String recharge(@RequestParam Double rechargeValue,@RequestParam Integer id){
        logger.info("come in recharge");
        BaseInfo baseInfo = memberService.memberRecharge(rechargeValue,id);
        return JSON.toJSONString(baseInfo);
    }

//    @PostMapping("/member/newMember")
//    @ResponseBody
//    public String newMember(Member member){
//        logger.info("come in newMember");
//        BaseInfo baseInfo = memberService.addNewMember(member);
//        return JSON.toJSONString(baseInfo);
//    }
//    @PostMapping("/member/updateMember")
//    @ResponseBody
//    public String updateMember(Member member){
//        logger.info("come in updateMember");
//        BaseInfo baseInfo = memberService.updateMember(member);
//        return JSON.toJSONString(baseInfo);
//    }

    @GetMapping("/member/getMemberSale/{id}")
    @ResponseBody
    public String getMemberSale(@PathVariable Integer id){
        logger.info("come in getMemberByCardOrMobile");
        BaseInfo baseInfo = memberService.getMemberSale(id);
        return JSON.toJSONString(baseInfo);
    }


}
